 package org.i1510.base.utils.web;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;


public class WebUtils {
	private static final Logger logger = LoggerFactory.getLogger(WebUtils.class);
	
	public static ResultMapper getMapper4Errors(BindingResult errors){
		ResultMapper mapper = ResultMapper.generateFailure();
		List<FieldError> errorList = errors.getFieldErrors();
		for(int i=0; i<errorList.size(); i++){
			FieldError error = errorList.get(i);
			logger.info(error.toString());
			mapper.appendResult(error.getField(), error.getDefaultMessage());
		}
		return mapper;
	}
	
	/**
	 * 将request的Attribute转化为map
	 * @param request
	 * @return
	 * @author Rambo
	 * @date 2013-10-25 
	 */
	public static Map<String, Object> toAttributeMap(HttpServletRequest request){
		Map<String, Object> result = new HashMap<String, Object>();
		Enumeration<String> enumeration = request.getAttributeNames();
		while(enumeration.hasMoreElements()){
			String key = enumeration.nextElement();
			result.put(key, request.getAttribute(key));
		}
		return result;
	}
}
